package com.zgt.web.action;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zgt.model.Admin;
import com.zgt.model.Student;
import com.zgt.service.AdminService;
import com.zgt.util.MD5;
import com.zgt.util.Page;
import com.zgt.web.AbstractAction;

@Controller("adminAction")
@Scope("prototype")
public class AdminAction extends AbstractAction implements ModelDriven<Admin> {

	private Admin admin = new Admin();
	private AdminService adminService;
	private MD5 m = new MD5();
	private Page page = new Page();
	private Map request = (Map) ActionContext.getContext().get("request");
	private Map session = ActionContext.getContext().getSession();
	private String submitFlag;

	public String add() {
		if (getSubmitFlag() == null) {
			return INPUT;
		}
		admin.setPassword(m.getMD5ofStr(admin.getPassword()));
		adminService.addAdmin(admin);
		request.put("url", "admin_list.action");
		return SUCCESS;
	}

	public String delete() {
		adminService.deleteAdminByid(admin.getId());
		request.put("url", "admin_list.action");
		return SUCCESS;
	}

	public String edit() {
		admin = adminService.getAdminByid(admin.getId());
		request.put("admin", admin);
		return INPUT;

	}

	public AdminService getAdminService() {
		return adminService;
	}

	public Admin getModel() {
		return admin;
	}

	public Page getPage() {
		return page;
	}

	public String getSubmitFlag() {
		return submitFlag;
	}

	@SuppressWarnings("unchecked")
	public String list() {

		request.put("page", adminService.admins(page));
		return INPUT;
	}

	public String login() {
		admin.setUsername(admin.getUsername());
		admin.setPassword(m.getMD5ofStr(admin.getPassword()));
		admin = adminService.checkLogin(admin);
		if (admin != null) {
			session.put("user", admin);
			session.put("scope", "admin");
			return "login";
		}
		return ERROR;
	}

	public String logout() {
		session.clear();
		return ERROR;
	}

	@Resource
	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public void setSubmitFlag(String submitFlag) {
		this.submitFlag = submitFlag;
	}

	public String update() {
		if (!admin.getPassword().trim().isEmpty()
				&& admin.getPassword() != null) {
			admin.setPassword(m.getMD5ofStr(admin.getPassword()));
		} else {
			Admin temp = adminService.getAdminByid(admin.getId());
			admin.setPassword(temp.getPassword());
		}
		adminService.changePassword(admin);
		request.put("url", "admin_list.action");
		return SUCCESS;
	}

}
